package com.leetcode.程序员面试金典.hard;

/**
 * @author 覃国强
 * @date 2022-01-28 14:46
 */
public class 面试题_16_08_整数的英语表示 {

  public static void main(String[] args) {
    Solution solution = new Solution();
    int num = 100;
    String words = solution.numberToWords(num);
    System.out.println("|" + words + "|");
  }

  static
  class Solution {

    // 0 ~ 19
    public static final String[] singleAndTeens = {"", "One", "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
        "Sixteen", "Seventeen", "Eighteen", "Nineteen"};

    // 整十数
    public static final String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
        "Seventy", "Eighty", "Ninety"};

    public static final String ZERO = "Zero";

    public static final String hundred = "Hundred";

    public static final String[] thousands = {"", " Thousand", " Million", " Billion"};

    public String numberToWords(int num) {
      if (num == 0) {
        return ZERO;
      }

      String words = "";
      for (int i = 0; i < thousands.length && num != 0; ++i, num /= 1000) {
        int cur = num % 1000;
        if (cur == 0) {
          continue;
        }
        String word = num1To999(cur);
        words = addWord(word + thousands[i], words);
      }
      return words;
    }

    private String num1To19(int num) {
      if (num < 1 || num > 19) {
        return "";
      }
      return singleAndTeens[num];
    }

    private String num1To99(int num) {
      if (num < 1 || num > 99) {
        return "";
      }
      if (num < 20) {
        return num1To19(num);
      }
      int high = num / 10;
      int low = num % 10;
      return addWord(tens[high], num1To19(low));
    }

    private String num1To999(int num) {
      if (num < 1 || num > 999) {
        return "";
      }
      if (num < 100) {
        return num1To99(num);
      }
      int high = num / 100;
      int low = num % 100;
      return addWord(singleAndTeens[high] + " " + hundred, num1To99(low));
    }

    private String addWord(String cur, String word) {
      if (cur.isEmpty()) {
        return word;
      }
      if (word.isEmpty()) {
        return cur;
      }
      return cur + " " + word;
    }
  }

}
